package example.websocket;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

//import javax.servlet.http.HttpServletRequest;
//import javax.websocket.*;
//import javax.websocket.server.HandshakeRequest;
//import javax.websocket.server.ServerEndpoint;
//import javax.websocket.server.ServerEndpointConfig;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


//@ServerEndpoint(value = "/tws")
public class TestWebSocketServer {
   /* private static final Set<Session> sessions = new HashSet<Session>();
    private static  ScheduledExecutorService scheduler ;
    private static Boolean ifopen = false;
    public TestWebSocketServer() {
        System.out.println("TestWebSocketServer 构造函数");
    }
    private void init(Session session) {
        System.out.println("init");
        autoSendItem();


    }
    @OnOpen
    public  void onOpen( Session session,EndpointConfig config) throws IOException {
        System.out.println("onOpen");
        //获得ip
//        HttpServletRequest request = (HttpServletRequest) config.getUserProperties().get(HttpServletRequest.class.getName());
//        String clientIp = request.getRemoteAddr();
//        System.out.println("新连接来自：" + clientIp);
//        URI uri = session.getRequestURI();
//        System.out.println(uri.getPath());
//
//       // String ip = session.getUserProperties().get("javax.websocket.endpoint.remoteAddress").toString();
        for (String key : session.getUserProperties().keySet()) {
            System.out.println(key);
            System.out.println(session.getUserProperties().get(key));
        }

//        System.out.println(ip);
        sessions.add(session);

        System.out.println("总数="+sessions.size());

//        autoSendItem();


    }
    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
//        System.out.println("onmessage"+message);

//        MeetingItem mi =  MeetingItemCantainer.getInstance().getMeetingItem("John");
//        mi.addLike();
//        session.getBasicRemote().sendText(JSON.toJSONString(mi));
//        session.getBasicRemote().sendText(JSON.toJSONString(mi));
//        for (int i = 0; i < 100; i++)
        {
            sendToAll(message);
        }

//        System.out.println("开始发送");
//        synchronized (this) {
//            System.out.println("开始发送中");
//            sendToAll(message);
//            System.out.println("开始发送结束");
//        }

//        sendToAll(message);
//        session.getBasicRemote().sendText("test");
//        for (Session session_temp : sessions) {
//            session_temp.getBasicRemote().sendText(message);
//        }

    }


    public void autoSendItem()
    {
        System.out.println("autoSendItem");
        synchronized (ifopen) {
            if (ifopen)
                return;
            ifopen = true;
            // 在启动时，调度一个定时任务，每隔一段时间向客户端发送消息
            scheduler = Executors.newScheduledThreadPool(1);
            scheduler.scheduleAtFixedRate(() -> {
                System.out.println("auto send .");

                MeetingItem mi = MeetingItemCantainer.getInstance().getNextItem();
                for (Session session_temp : sessions) {
                    if (session_temp.isOpen())
                        try {
                            synchronized (session_temp) {
                                session_temp.getBasicRemote().sendText(JSON.toJSONString(mi));
                            }
                        } catch (Exception e) {
                            System.out.println("发送错误：" + e.getMessage());
                            System.err.println(e.getMessage());
                        }
                }
//            try {
//               System.out.println("auto send.");
//            }
//            catch (Exception e) {
//                e.printStackTrace();
//            }
            }, 0, 2, TimeUnit.SECONDS); // 每隔10秒发送一次消息
        }

    }
    protected void shutdown() {
        scheduler.shutdown();
        ifopen = false;
    }

    protected   void sendToAll(String message) throws IOException {
        synchronized (sessions)
        {
            try {
                String str = JSON.toJSONString(message);

//            System.out.println(str);
                JSONObject strjson = JSON.parseObject(message);
//            System.out.println(strjson);
                if (strjson.getString("type").equals("1")) {
//                    String id = strjson.getString("name");

                    MeetingItem mi = MeetingItemCantainer.getInstance().getCurrentItem();

                    mi.addLike();
                    ;
//                    System.out.println("总数=" + sessions.size());
                    for (Session session_temp : sessions) {
                        if (session_temp.isOpen())
                            try {
                                synchronized (session_temp)
                                {
                                    session_temp.getBasicRemote().sendText(JSON.toJSONString(mi));
                                }
                            } catch (Exception e) {
                                System.out.println("发送错误：" + e.getMessage());
                                System.err.println(e.getMessage());
                            }
                    }

                } else if (strjson.getString("type").equals("2")) {
                    String id = strjson.getString("name");

                    MeetingItem mi = MeetingItemCantainer.getInstance().getMeetingItem(id);

                    mi.addUnLike();

                    for (Session session_temp : sessions) {


                        session_temp.getBasicRemote().sendText(JSON.toJSONString(mi));
                    }
                }

                else if(strjson.getString("type").equals("3"))
                {
                    MeetingItem mi = MeetingItemCantainer.getInstance().getNextItem();
                    for (Session session_temp : sessions) {
                        if (session_temp.isOpen())
                            try {
                                synchronized (session_temp)
                                {
                                    session_temp.getBasicRemote().sendText(JSON.toJSONString(mi));
                                }
                            } catch (Exception e) {
                                System.out.println("发送错误：" + e.getMessage());
                                System.err.println(e.getMessage());
                            }
                    }
                }

                else if(strjson.getString("type").equals("4"))
                {
                    MeetingItem mi = MeetingItemCantainer.getInstance().getPreItem();
                    for (Session session_temp : sessions) {
                        if (session_temp.isOpen())
                            try {
                                synchronized (session_temp)
                                {
                                    session_temp.getBasicRemote().sendText(JSON.toJSONString(mi));
                                }
                            } catch (Exception e) {
                                System.out.println("发送错误：" + e.getMessage());
                                System.err.println(e.getMessage());
                            }
                    }
                }
                else if(strjson.getString("type").equals("5"))
                {
                        autoSendItem();
                }
                else if(strjson.getString("type").equals("6"))
                {
                        shutdown();
                }

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason){

        System.out.print(closeReason.getReasonPhrase());
        System.out.println("onClose");
        sessions.remove(session);
    }

    @OnError
    public void onError(Session session, Throwable throwable){


        System.out.println("error");
        System.out.println(throwable.getMessage());
        System.out.println(throwable.toString());
        System.out.println(throwable.getCause());
        System.out.println("剩余连接="+sessions.size());
//        throwable.printStackTrace();
    }

    public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
        @Override
        public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request.getHttpSession();
            config.getUserProperties().put(HttpServletRequest.class.getName(), httpServletRequest);
        }
    }
*/
}
